package com.shsubway.activity.manger;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.shsubway.R;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.PostEntity;
import com.shsubway.model.StaffEntity;
import com.shsubway.utils.Constant;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 添加个修改员工共用界面
 */
public class AddStaffActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_name)
    MaterialEditText userName;
    @BindView(R.id.user_phone)
    MaterialEditText userPhone;
    @BindView(R.id.my_spinner)
    Spinner mySpinner;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    AndroidNextInputs inputs;
    List<PostEntity> mItems;
    int pos = 1;
    Intent intent;
    Bundle bundle;
    StaffEntity staffEntity;
    @BindView(R.id.user_home_phone)
    MaterialEditText userHomePhone;
    @BindView(R.id.user_home_address)
    MaterialEditText userHomeAddress;
    int TYPE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> {
            setResult(1);
            finish();
        });
        mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                pos = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initView() {
        mItems = new ArrayList<>();
        intent = getIntent();
        bundle = intent.getExtras();
        TYPE = intent.getIntExtra(Constant.TYPE, 0);
        setTitleBar(toolbar, TYPE==0?"添加新员工":"修改员工信息");
        staffEntity = (StaffEntity) bundle.getSerializable(Constant.STAFFENTITY);
        inputs = new AndroidNextInputs();
        inputs.add(userName, StaticScheme.NotBlank().msgOnFail("姓名不能为空"));
        inputs.add(userPhone, StaticScheme.NotBlank().msgOnFail("手机号码不能为空"), StaticScheme.ChineseMobile().msgOnFail("请输入正确的手机号码"));
        inputs.add(userHomePhone, StaticScheme.NotBlank().msgOnFail("紧急联系人手机号码不能为空"), StaticScheme.ChineseMobile().msgOnFail("请输入正确的手机号码"));
        inputs.add(userHomeAddress, StaticScheme.NotBlank().msgOnFail("家庭地址不能为空"));

        addDate();
    }

    private void addDate() {
        BmobQuery<PostEntity> query = new BmobQuery<>();
        query.setLimit(100);
        query.order("createdAt")
                .findObjects(new FindListener<PostEntity>() {
                    @Override
                    public void done(List<PostEntity> object, BmobException e) {
                        if (e == null) {
                            // ...
                            mItems.clear();
                            mItems.addAll(object);
                            setSpinner();
                            Log.e("oh==", object.toString());
                        } else {
                            // ...
                            Log.e("e==", e.toString());
                        }
                    }
                });
    }

    private void setSpinner() {

        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getDate());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        mySpinner.setAdapter(adapter);
        if (TYPE == 1) {
            initData();
        } else {
            mySpinner.setSelection(pos, true);
        }
    }

    private void initData() {
        pos = staffEntity.getStaff_permissions();
        mySpinner.setSelection(pos - 1, true);
        userName.setText(staffEntity.getStaff_name());
        userPhone.setText(staffEntity.getStaff_phone());
        userHomePhone.setText(staffEntity.getStaff_phone());
        userHomeAddress.setText(staffEntity.getStaff_address());
    }

    private List<String> getDate() {
        List<String> stringList = new ArrayList<>();
        for (PostEntity postEntity : mItems) {
            stringList.add(postEntity.getPost());
        }
        return stringList;
    }

    @OnClick(R.id.fab)
    public void onClick() {
        if (inputs.test()) {
            if (pos == 0) {
                toast("最高管理人员不能设置");
            } else {
                if (TYPE == 1) {
                    staffEntity.setStaff_name(userName.getText().toString().trim());
                    String phone = userPhone.getText().toString().trim();
                    staffEntity.setStaff_phone(phone);
                    staffEntity.setStaff_permissions(pos + 1);
                    staffEntity.setStaff_post(mItems.get(pos).getPost());
                    staffEntity.setStaff_home_phone(userHomePhone.getText().toString().trim());
                    staffEntity.setStaff_address(userHomeAddress.getText().toString().trim());
                    staffEntity.update(staffEntity.getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                setResult(1);
                                finish();
                            } else {
                                toast("修改失败");
                            }
                        }
                    });
                } else {
                    StaffEntity staff = new StaffEntity();
                    staff.setStaff_name(userName.getText().toString().trim());
                    String phone = userPhone.getText().toString().trim();
                    staff.setStaff_phone(phone);
                    staff.setStaff_pwd(phone.substring(phone.length() - 6, phone.length()));
                    staff.setStaff_permissions(pos + 1);
                    staff.setStaff_post(mItems.get(pos).getPost());
                    staff.setGroupId(staffEntity.getGroupId());
                    staff.setStaff_home_phone(userHomePhone.getText().toString().trim());
                    staff.setStaff_address(userHomeAddress.getText().toString().trim());

                    staff.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                setResult(1);
                                finish();
                            } else {
                                toast("添加失败");
                            }
                        }
                    });
                }

            }
        }
    }
}
